<template>
  <el-select
    v-model="currentField"
    clearable
    filterable
    remote
    :remote-method="search"
    :placeholder="getDefValue(currentArgs.placeholder, '输入题库名称搜索')"
    :collapse-tags="collapseTagsValue"
    :multiple="multipleValue"
    :multiple-limit="getDefValue(currentArgs.max, 0)"
    :disabled="disabledValue"
    :loading="loading"
    loading-text="正在搜索题库"
    no-data-text="无相关题库"
    :style="style"
    @change="$emit('update:value', currentField)"
    @focus="eventFocus"
  >
    <el-option v-for="option in selectOptions" :key="option.value" :value="option.value" :label="option.title" />
  </el-select>
</template>
<script>
export default {
  props: {
    value: {
      type: [String, Number, Array],
      default: ''
    },
    args: {
      type: Object,
      required: true
    },
    formDatas: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      currentField: this.value,
      currentArgs: this.args,
      loading: false,
      selectOptions: [
        {
          value: this.value,
          title: this.formDatas.question_bank_title
        }
      ]
    };
  },
  computed: {
    disabledValue() {
      if (this.currentArgs.disabled == '1') {
        return true;
      }

      return null;
    },
    collapseTagsValue() {
      if (this.currentArgs.megre_tags == '1') {
        return true;
      }

      return null;
    },
    multipleValue() {
      if (this.currentArgs.multiple == '1') {
        return true;
      }

      return null;
    },
    style() {
      return this.currentArgs.css ? this.currentArgs.css : {};
    }
  },
  watch: {
    value: {
      handler(now, old) {
        this.currentField = now;
      }
    }
  },
  methods: {
    getDefValue(defValue, defaultValue) {
      return this.$util.getDefValue(defValue, defaultValue);
    },
    eventFocus: function() {
      this.search();
    },
    search: function(keyword) {
      this.loading = true;
      this.$http.get(
        '/exam/admin/question/bank/search',
        {
          keyword
        },
        ({ data }) => {
          this.loading = false;
          var list = [];
          data.forEach(function(item) {
            list.push({
              title: item.title,
              value: item.id
            });
          });
          this.selectOptions = list;
        },
        _ => {
          this.$message.error('搜索失败');
          this.loading = false;
        },
        false
      );
    }
  }
};
</script>
